package com.ruoyi.plus.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.plus.controller.po.SysUserLockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/monitor/userLock")
public class SysUserLockController extends BaseController {

    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("@ss.hasPermi('monitor:userLock:list')")
    @GetMapping("/lockList")
    public TableDataInfo lockList(String account) {
        Collection<String> keys = null;
        String prefix = CacheConstants.PWD_ERR_CNT_KEY;
        if (StringUtils.isEmpty(account)) {
            keys = redisCache.keys(prefix + "*");
        } else {
            keys = redisCache.keys(prefix + account);
        }
        List<SysUserLockVo> collect = keys.stream().map(e -> {
            String substring = e.substring(prefix.length());
            SysUserLockVo vo = new SysUserLockVo();
            vo.setAccount(substring);
            return vo;
        }).collect(Collectors.toList());

        return getDataTable(collect);
    }

    @PreAuthorize("@ss.hasPermi('monitor:userLock:unlock')")
    @Log(title = "解锁用户", businessType = BusinessType.FORCE)
    @PostMapping("/unlock/{account}")
    public AjaxResult unlock(@PathVariable String account) {
        redisCache.deleteObject(CacheConstants.PWD_ERR_CNT_KEY + account);
        return AjaxResult.success();
    }
}
